package com.zja.servlet;


import com.zja.model.Article;
import com.zja.model.JsonResponse;
import com.zja.service.ArticleService;
import com.zja.service.Impl.ArticleServiceImpl;
import com.zja.util.ServletUtil;


import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;
/**
 * @author JA
 * @date: 2025/5/4
 * description:更新文章
 */
@WebServlet("/api/article/update")
public class UpdateArticleServlet extends HttpServlet {
    private final ArticleService articleService = new ArticleServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");

        Long id = Long.valueOf(req.getParameter("id"));
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Long kbId = Long.valueOf(req.getParameter("knowledgeBaseId"));

        Article article = articleService.getArticleById(id);
        if (article == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("文章不存在"));
            return;
        }

        article.setTitle(title);
        article.setContent(content);
        article.setKnowledgeBaseId(kbId);
        article.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

        boolean success = articleService.updateArticle(article);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("更新成功"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("更新失败"));
        }
    }
}
